package com.Java.train.business.service.Impl;

import com.Java.train.business.entity.*;
import com.Java.train.business.service.TrainCarriageService;
import com.Java.train.business.service.TrainSeatService;
import com.Java.train.business.service.TrainStationService;
import com.Java.train.common.response.CommonResp;
import com.Java.train.business.entity.DTO.TrainDTO;
import com.Java.train.business.req.TrainQueryReq;
import com.Java.train.common.exception.BusniessException;
import com.Java.train.common.exception.BusniessExceptionEnum;
import com.Java.train.common.response.PageResp;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.Java.train.business.mapper.TrainMapper;
import com.Java.train.business.service.TrainService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.Java.train.common.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.date.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
/**
* 车次 服务实现类
*
* @author luomoxingchen
* @since 2024-09-22
*/
@Service
public class TrainServiceImpl extends ServiceImpl<TrainMapper, Train> implements TrainService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainService.class);

    @Autowired
    TrainMapper trainMapper;
    @Resource
    TrainStationService trainStationService;
    @Resource
    TrainCarriageService trainCarriageService;
    @Resource
    TrainSeatService trainSeatService;

    @Override
    public PageResp<TrainDTO> queryList(TrainQueryReq trainQueryReq){
        // 1.获取当前用户id信息
        //        Long id = LoginMemberContext.getId();
        // 2.查询数据库中是否存在当前信息（id）
        LOG.info("查询页码：{}", trainQueryReq.getPage());
        LOG.info("每页条数：{}", trainQueryReq.getSize());
        PageHelper.startPage(trainQueryReq.getPage(),trainQueryReq.getSize());
        List<Train> trains = list();
        if(trains == null || CollUtil.isEmpty(trains)){
            // 返回空列表
            return new PageResp<TrainDTO>();
//            throw new BusniessException(BusniessExceptionEnum.BUSINESS_TRAIN_NOT_EXITS);
        }

        // 3 分析分页信息
        // 3.1 获取分页总条数和页数
        PageInfo<Train> pageInfo = new PageInfo<>(trains);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // 3.2 转为封装后的返回值并封装到分页返回值中
        List<TrainDTO> list = BeanUtil.copyToList(trains, TrainDTO.class);
        PageResp<TrainDTO> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        // 4.返回查询到的信息
        return pageResp;
    }

    @Override
    public CommonResp<Object> modify(Train train) {
        Long id = train.getId();
        DateTime dateTime = DateTime.now();
        if(ObjectUtil.isNull(id)){
            // 查重
            Train TrainDB = getTrainByUnique(train.getCode());
            if(ObjectUtil.isNotEmpty(TrainDB)){
                throw new BusniessException(BusniessExceptionEnum.BUSINESS_TRAIN_ALREADY_EXITS);
            }

            train.setId(SnowFlakeUtil.getSnowFlakeNextId());
            train.setCreateTime(dateTime);
            train.setUpdateTime(dateTime);
            boolean save = save(train);
            return new CommonResp<>(save);
        } else {
            train.setUpdateTime(dateTime);
            boolean update = updateById(train);
            return new CommonResp<>(update);
        }
    }

    @Override
    @Transactional
    public CommonResp<Object> remove(String ids) {
        if (StrUtil.isNotEmpty(ids)) {
            String[] array = ids.split(",");
            if (!CollectionUtils.isEmpty(Arrays.asList(array))) {
                // 删除ids所有有关的信息
                Train train = getById(ids);
                String trainCode = train.getCode();
                trainStationService.remove(new LambdaQueryWrapper<TrainStation>().eq(TrainStation::getTrainCode, trainCode));
                trainCarriageService.remove(new LambdaQueryWrapper<TrainCarriage>().eq(TrainCarriage::getTrainCode, trainCode));
                trainSeatService.remove(new LambdaQueryWrapper<TrainSeat>().eq(TrainSeat::getTrainCode, trainCode));
                return new CommonResp<>(trainMapper.deleteBatchIds(Arrays.asList(array)));
            }
        }
        return new CommonResp<>(Collections.EMPTY_LIST);
    }


    @Override
    public List<TrainDTO> queryAll() {
        List<Train> trains = list();
        if(trains == null || CollUtil.isEmpty(trains)){
            throw new BusniessException(BusniessExceptionEnum.BUSINESS_TRAIN_NOT_EXITS);
        }
        // 3.2 转为封装后的返回值并封装到分页返回值中
        List<TrainDTO> list = BeanUtil.copyToList(trains, TrainDTO.class);
        // 4.返回查询到的信息
        return list;
    }

    // 通过唯一键校验查重
    private Train getTrainByUnique(String code) {
        LambdaQueryWrapper<Train> wrapper = new LambdaQueryWrapper<>();
        Train one = getOne(wrapper.eq(Train::getCode, code));
        return one;
    }
}


